package com.hiwetop.cp;

import com.fj.hiwetoptools.StringUtil;

import javax.swing.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.List;

/**
 * Created by linyu on 2016/12/9.
 */
public class VoteConnectionExample {
    private List<String> cookies;
    private HttpURLConnection conn;

    private final String USER_AGENT = "Mozilla/5.0";



    protected String sendPost(String url, String postParams,String referer,String cookies) throws Exception {

        URL obj = new URL(url);
        conn = (HttpURLConnection) obj.openConnection();

        // Acts like a browser
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Host", "wx.e7wei.net");
        conn.setRequestProperty("User-Agent", USER_AGENT);
        conn.setRequestProperty("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        conn.setRequestProperty("Accept-Language", "zh-CN,en-US;q=0.8");
        conn.setRequestProperty("Cookie", cookies);

        conn.setRequestProperty("Accept-Charset", "utf-8");
        conn.setRequestProperty("contentType", "utf-8");
        conn.setRequestProperty("Connection", "keep-alive");
        conn.setRequestProperty("Referer", referer);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));

        conn.setDoOutput(true);
        conn.setDoInput(true);

        // Send post request
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + postParams);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in =
                new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        System.out.println(response.toString());
        in.close();
        // System.out.println(response.toString());
        return response.toString();
    }

    protected String GetPageContent(String url,String cookies) throws Exception {

        URL obj = new URL(url);
        conn = (HttpURLConnection) obj.openConnection();

        // default is GET
        conn.setRequestMethod("GET");

        conn.setUseCaches(false);
        conn.setRequestProperty("Cookie", cookies);
        // act like a browser
        conn.setRequestProperty("Accept-Charset", "utf-8");
        conn.setRequestProperty("contentType", "utf-8");
        conn.setRequestProperty("User-Agent", USER_AGENT);
        conn.setRequestProperty("Referer", "http://wx.e7wei.net/index/detail/vid/465/uid/4051.html");
        conn.setRequestProperty("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
//        if (cookies != null) {
//            for (String cookie : this.cookies) {
//                conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
//            }
//        }
        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);
        setCookies(conn.getHeaderFields().get("Set-Cookie"));
        // 从外界想手机应用内传递数据----通过输入流获取图片数据
        InputStream inputStream = conn.getInputStream();
        // 从输入流中获取图片的二进制数据----readInputStream()
        byte[] data = readInputStream(inputStream);
        // 将数据保存到应用文件的根目录下，文件名为系统时间
        File inageFile = new File("code.jpg");
        //通过文件输出流将二进制数据写到文件中去
        FileOutputStream fileOutputStream = new FileOutputStream(inageFile);
        //通过write()写进文件中去
        fileOutputStream.write(data);
        fileOutputStream.close();

        return "";

    }

    public List<String> getCookies() {
        return cookies;
    }

    public void setCookies(List<String> cookies) {
        this.cookies = cookies;
    }

    // 读取输入流的方法
    public static byte[] readInputStream(InputStream inSream) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 定义一个缓冲区
        byte[] buffer = new byte[1024];
        int len = 0;
        // 不断的从流里读取数据---while循环---nSream.read(buffer)表示从流里读取数据到缓冲区
        // 读取到末尾时，返回值是-1；
        while ((len = inSream.read(buffer)) != -1) {
            // 将缓冲区的数据写到输出流中
            byteArrayOutputStream.write(buffer, 0, len);
        }
        inSream.close();
        return byteArrayOutputStream.toByteArray();
    }



}
